package com.xxx.common.web.interceptor;

import com.xxx.common.base.constants.MdcKey;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class TenantIdInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantId = request.getHeader(MdcKey.TENANT_ID);

        if (StringUtils.isNotBlank(tenantId)) {
            MDC.put(MdcKey.TENANT_ID, tenantId);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MDC.remove(MdcKey.TENANT_ID);
        MDC.remove(MdcKey.TABLE_NAME);
    }

}